
import React, { Component } from 'react';
import Input from './Input';
import List from './List'

export default class ToDoList extends Component {

    state = {
        list: JSON.parse(localStorage.getItem('todoList')) || [],
    };

    addItem = (e) => {
        //setState是异步的：体现在存储时存上一个==>所以改成现在的每次都是arr保存当前所有的（除去一步）
        if (e.keyCode == 13) {
            let arr = [{ title: e.target.value, time: Date.now() }, ...this.state.list]
            this.setState({
                list: arr
            }, () => {

                localStorage.setItem('todoList', JSON.stringify(arr));
                // localStorage.setItem('todoList',JSON.stringify(this.state.list));

                console.log(this.state.list);
            })
        }
    }
    delIteml = (i) => {
        console.log(i);

        //list地址未变，状态对比比较地址，有问题
        // this.state.list.splice(index,1);
        // this.setState({
        //     list:this.state.list
        // })
        // filter为真留下,创建新数组
        let newList = this.state.list.filter((item, index) => i != index)
        this.setState({ list: newList })
        localStorage.setItem('todoList', JSON.stringify(newList))
    }
    del = (i) => {

        return () => { console.log(i) }
    }
    saveData = (type) => {
        return (e) => {
            this.setState({
                [type]: e.target.value//状态更新：状态合并==>用新的对象替换
            })
        }
    }

    render() {
        const { list } = this.state;
//React单向数据流，只能从父组件到子组件
        return (
            <div>

                <Input addItem={this.addItem} />
                <List list={list} delIteml={this.delIteml} del= {this.del}/>
                {/* <List list={list} delIteml={this.delIteml} delToDo= {this.del}/> */}

            </div>
        )
    }
}
